package org.finmanager.core;

import org.finmanager.budget.BudgetCategoryComboBoxModel;
import org.finmanager.data.CategoryList;

import java.util.ArrayList;
import java.util.Observable;

/**
 * Created by Kelvin on 26/4/2014.
 */

//defining models related to category to be further used easily
public class CategoryModel extends Observable {
	private FinManager finManager;

	private CategoryTableModel categoryTableModel;
	private CategoryComboBoxModel categoryComboBoxModel;
	private BudgetCategoryComboBoxModel budgetCategoryComboBoxModel;

	private ArrayList<CategoryComboBoxModel> categoryComboBoxModels = new ArrayList<CategoryComboBoxModel>();

	public CategoryModel(FinManager finManager) {
		this.finManager = finManager;

		this.categoryTableModel = new CategoryTableModel(this);
		this.categoryComboBoxModel = new CategoryComboBoxModel(this);
		this.budgetCategoryComboBoxModel = new BudgetCategoryComboBoxModel(this);

		categoryComboBoxModels.add(categoryComboBoxModel);
		categoryComboBoxModels.add(budgetCategoryComboBoxModel);
	}

	public CategoryList getCategoryList() {
		return finManager.getCategoryList();
	}

	public CategoryTableModel getCategoryTableModel() {
		return categoryTableModel;
	}

	public CategoryComboBoxModel getCategoryComboBoxModel() {
		return categoryComboBoxModel;
	}

	public BudgetCategoryComboBoxModel getBudgetCategoryComboBoxModel() {
		return budgetCategoryComboBoxModel;
	}

	public void addCategory(Category category) {
		finManager.getCategoryList().addCategory(category);
		int index = finManager.getCategoryList().getCategoryCount() - 1;
		categoryTableModel.fireTableRowsInserted(index, index);

		for (CategoryComboBoxModel model : categoryComboBoxModels) {
			model.fireIntervalAdded(categoryComboBoxModel, index, index);
		}

		setChanged();
		notifyObservers(category);
		clearChanged();
	}

	public void deleteCategory(int index) {
		Category category = finManager.getCategoryList().getCategory(index);
		finManager.getCategoryList().deleteCategory(index);
		categoryTableModel.fireTableRowsDeleted(index, index);

		for (CategoryComboBoxModel model : categoryComboBoxModels) {
			model.fireIntervalAdded(categoryComboBoxModel, index, index);
		}

		setChanged();
		notifyObservers(category);
		clearChanged();
	}
}
